$(document).ready(function () {
    /*==插件网址http://www.layui.com//==*/
    layui.use(['form', 'laydate', 'upload', 'laypage', 'layer', 'table', 'element'], function () {
        var $ = layui.jquery, //调用layui内置jquery
            form = layui.form, //表单
            element = layui.element, //Tab的切换功能，切换事件监听等，需要依赖element模块
            laydate = layui.laydate, //日期
            laypage = layui.laypage, //分页
            upload = layui.upload, //上传
            table = layui.table, //表格
            layer = layui.layer; //弹层

        //添加验证
        form.verify({
            required: function (value, item) { //value：表单的值、item：表单的DOM对象
                var name = $(item).attr('placeholder');
                name = (name != null && name != '') ? name : $(item).attr('name');
                if (value == '') {
                    return 'Please Enter ' + name;
                }
            }
        });

        //pricing页面表格初始化 
        //转换静态表格
        table.init('priceData1', {
            limit: 100
        });
        table.init('priceData2', {
            limit: 100
        });
        table.init('priceData3', {
            limit: 100
        });
        table.init('priceData4', {
            limit: 20
        });

        //*************报价单开始***************//
        if ($('#xunjiaFormBox').length > 0) {
            form.on('select(productCategory)', function (obj) {
                if (obj.value != '') {
                    vm.changeProductCategoryOrProduct(parseInt(obj.value));
                }
            });

            var _productConfig = [];
            var _priceConfig = [];
            var _canSubmitQuote = true;
            var vm = new Vue({
                el: '#xunjiaFormBox',
                data: {
                    productCategoryNode: [],
                    productNode: [],
                    quantityNode: null,
                    sizeNode: null,
                    embroideryCoverageNode: null,
                    backingNode: null,
                    borderAndEdgeNode: null,
                    artworkIndex: 0,
                    tradeGategroyIds: null,
                    orderItem: {
                        name: '',
                        email: '',
                        phone: '',
                        productCategoryId: 0,
                        productCategory: '',
                        productId: 0,
                        product: '',
                        fileList: [],
                        youMessage: '',
                        size: '',
                        quantity: '',
                        embroideryCoverage: '',
                        specialOptionIds: '',
                        specialOptionList: [
                            // {cateId:0,cateName:'Backing',itemId:0,itemName:'No Backing',photo:'',rate:'10',extraAmount:'5'}
                        ]
                    }
                },
                created: function () {
                    //创建前，加载需要的数据
                    //layer.load();
                    var me = this;

                    var productCategoryId = $('#productCategoryId').val();
                    var productCategory = $('#productCategoryName').val();
                    var tradeGategroyIds = $('#tradeGategroyIds').val();

                    if (productCategoryId != undefined) {
                        me.orderItem.productCategoryId = productCategoryId;
                        me.orderItem.productCategory = productCategory;
                        me.tradeGategroyIds = tradeGategroyIds;

                        $.ajax({
                            type: "get",
                            url: "/api/quoteConfig.json",
                            success: function (data) {
                                layer.closeAll('loading');
                                $('#quoteFormLoading').addClass('hide');
                                $("[name='quoteForm']").removeClass('hide');
                                _priceConfig = data.priceConfigList;
                                me.initProduct(data.tradeConfigQuoteTree[1]);
                            },
                            error: function () {
                                layer.closeAll('loading');
                                $.zero.showErrorMsg('Sorry Server Lost');
                            }
                        });
                    }
                    else {
                        $.ajax({
                            type: "get",
                            url: "/api/quoteConfig.json?type=0&hasCategory=true",
                            success: function (data) {
                                layer.closeAll('loading');
                                $('#quoteFormLoading').addClass('hide');
                                $("[name='quoteForm']").removeClass('hide');
                                _priceConfig = data.priceConfigList;
                                me.initProductCategory(data.tradeConfigQuoteTree[1], data.productCategoryList);
                            },
                            error: function () {
                                layer.closeAll('loading');
                                $.zero.showErrorMsg('Sorry Server Lost');
                            }
                        });
                    }
                },
                methods: {
                    submitQuote: function (data) {
                        if (_canSubmitQuote === false) return;

                        if (data.field.name === '') {
                            $.zero.showErrorMsg('Please Enter Your Nmae');
                            $("input[name='name']").focus();
                            return;
                        }

                        if (data.field.email === '') {
                            $.zero.showErrorMsg('Please Enter Your Email');
                            $("input[name='email']").focus();
                            return;
                        }

                        var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                        if (!reg.test(data.field.email)) {
                            $.zero.showErrorMsg('Correct Mailbox Format');
                            $("input[name='email']").focus();
                            return;
                        }

                        this.orderItem.fileData = JSON.stringify(vm.orderItem.fileList);
                        vm.orderItem.size = data.field.size;

                        if (data.field.embroideryCoverage !== '') {
                            var embroideryCoverage = $.zero.find(vm.embroideryCoverageNode.children, 'name', data.field.embroideryCoverage);
                            vm.orderItem.embroideryCoverageId = embroideryCoverage.id;
                            vm.orderItem.embroideryCoverage = embroideryCoverage.name;
                        }

                        vm.orderItem.specialOptionList = [];
                        var specialOptionItem = [];
                        if (vm.backingNode !== null && data.field.backing !== '') {
                            specialOptionItem = $.zero.find(vm.backingNode.children, 'name', data.field.backing);
                            vm.orderItem.specialOptionList.push({
                                cateId: vm.backingNode.id,
                                cateName: vm.backingNode.name,
                                itemId: specialOptionItem.id,
                                itemName: specialOptionItem.name
                            });
                        }

                        if (vm.borderAndEdgeNode !== null && data.field.borderAndEdge !== '') {
                            specialOptionItem = $.zero.find(vm.borderAndEdgeNode.children, 'name', data.field.borderAndEdge);
                            vm.orderItem.specialOptionList.push({
                                cateId: vm.borderAndEdgeNode.id,
                                cateName: vm.borderAndEdgeNode.name,
                                itemId: specialOptionItem.id,
                                itemName: specialOptionItem.name
                            });
                        }

                        vm.orderItem.specialOptionData = JSON.stringify(vm.orderItem.specialOptionList);

                        _canSubmitQuote = false;

                        layer.load(2);
                        $.ajax({
                            type: "post",
                            url: "/api/addQuote",
                            data: vm.orderItem,
                            success: function (msg) {
                                layer.closeAll('loading');
                                if (msg.success) {
                                    console.log(msg);
                                    //layer.msg('ok');
                                    gtag_report_conversion_quote();
                                    //location.href = '/thankyou.html?quoteid=' + msg.result.id + '&t=' + msg.result.token;
                                    location.href = '/autoprice.html?quoteid=' + msg.result.id + '&t=' + msg.result.token;
                                }
                                else {
                                    $.zero.showValidationErrorMsg(msg);
                                }
                                _canSubmitQuote = true;
                            },
                            error: function () {
                                layer.closeAll('loading');
                                $.zero.showErrorMsg('Sorry Server Lost');
                                _canSubmitQuote = true;
                            }
                        });
                    },
                    initProductCategory: function (data1, data2) {
                        _productConfig = data1;
                        this.productCategoryNode = data2;

                        this.selectedProduct(null);
                        this.fromRender();
                    },
                    initProduct: function (data) {
                        _productConfig = data;
                        var productIds = this.tradeGategroyIds.split(',');
                        this.productCategoryNode = $.zero.where(_productConfig.children, function () {
                            return productIds.indexOf(this.id.toString()) != -1;
                        });
                        if (this.productCategoryNode != null) {
                            this.changeProduct(parseInt(productIds[0]));
                        }
                        else {
                            this.selectedProduct(null);
                        }

                        this.fromRender();
                    },
                    fromRender: function () {
                        this.$nextTick(function () {

                            ///* 注册表单的Artwork项 start*/
                            //$(".artioption dt").click(function () {
                            //    if ($(this).is(".active")) {
                            //        $(this).next().hide(0);
                            //        $(this).removeClass("active");
                            //    } else {
                            //        $(".optionItem dd").hide(0);
                            //        $(this).next().show(0);
                            //        $(this).addClass("active").siblings("dt").removeClass("active");
                            //    }
                            //})

                            //$(".radioitem span").click(function () {
                            //    var inddx = $(this).index();
                            //    $(this).addClass("ssel").siblings("span").removeClass("ssel");
                            //    $(".artioption dd").hide(0);
                            //    $(".artioption dt").removeClass("active");
                            //    $(".rowmodle .rowbox").eq(inddx).slideDown(800).siblings().slideUp(300);

                            //    if (inddx == 2) {
                            //        $(".rowmodle .rowbox").slideUp(300);
                            //    }
                            //})// 单选框 点击效果
                            ///* 注册表单的Artwork项 end*/

                            form.val('quoteForm', {
                                "size": '3'
                            });

                            form.val('quoteForm', {
                                'embroideryCoverage': '75%'
                            });

                            form.render();

                            //提交表单
                            form.on('submit(xunjiaSubmit)', function (data) {
                                vm.submitQuote(data);
                            });

                            /*api地址http://www.layui.com/doc/modules/upload.html */
                            var uploadInstFaceFile = upload.render({
                                elem: '#uploadFile', //绑定元素
                                accept: 'file', //允许上传的文件类型
                                //acceptMime: 'image/jpeg, image/jpg, image/png',//规定打开文件选择框时，筛选出的文件类型。
                                multiple: false, //允许多文件上传
                                exts: 'jpg|png|gif|bmp|jpeg|pdf|psd|tif|tiff|pic|pct|pga|eps|cdr|ai|hpgl|dxf|autocad',//允许上传的文件后缀
                                //auto: false, //选完文件后不要自动上传
                                //bindAction: '#xunjiaSubmit', //指定一个按钮触发上传
                                url: '/api/upload', //上传接口
                                number: 1,//设置同时可上传的文件数量
                                size: 10000, //最大允许上传的文件大小
                                progress: function (e, percent) {
                                    element.progress('progressBar', percent + '%');
                                },
                                choose: function (obj) {
                                    console.log('choose');
                                },
                                before: function (obj) {
                                    $('#uploadProgress').removeClass('hide');
                                },
                                done: function (res, index, upload) {
                                    if (res.success) {
                                        vm.orderItem.fileList.push(res.result);
                                    }
                                    else {
                                        $.zero.showErrorMsg(res.error.message);
                                    }
                                    $('#uploadProgress').addClass('hide');
                                    element.progress('progressBar', '0%');
                                },
                                error: function () {
                                    $.zero.showErrorMsg(res.error.message);
                                    $('#uploadProgress').addClass('hide');
                                    element.progress('progressBar', '0%');
                                }
                            });   //quote文件上传
                        });
                    },
                    changeProductCategoryOrProduct: function (id) {
                        if (this.tradeGategroyIds != null) {
                            this.changeProduct(id);
                        }
                        else {
                            this.changeProductCategory(id);
                        }
                    },
                    changeProductCategory: function (id) {
                        var productCategory = $.zero.find(this.productCategoryNode, { 'id': id });
                        this.orderItem.productCategoryId = id;
                        this.orderItem.productCategory = productCategory.alias;

                        var productItem = null;
                        if (productCategory.tradeGategroyIds != null) {
                            var tradeProductIds = productCategory.tradeGategroyIds.split(',');

                            if (tradeProductIds.length > 0) {
                                productItem = $.zero.find(_productConfig.children, function () {
                                    return this.id.toString() == tradeProductIds[0];
                                });
                            }
                        }
                        this.selectedProduct(productItem);
                    },
                    changeProduct: function (id) {
                        var productItem = $.zero.find(_productConfig.children, { 'id': id });
                        this.selectedProduct(productItem);
                    },
                    selectedProduct: function (productItem) {
                        if (productItem == null) {
                            productItem = _productConfig.children[0];
                        }

                        this.orderItem.productId = productItem.id;
                        this.orderItem.product = productItem.name;

                        this.quantityNode = null;
                        this.embroideryCoverageNode = null;
                        this.orderItem.embroideryCoverageId = 0;
                        this.orderItem.embroideryCoverage = '';
                        this.orderItem.quantity = '';

                        this.sizeNode = $.zero.where(_priceConfig, { 'categoryId': this.orderItem.productId });
                        var customize = $.zero.find(productItem.children, { 'name': 'Customize' });
                        if (customize != null) {
                            this.quantityNode = $.zero.find(customize.children, { 'name': 'Quantity' });
                            this.embroideryCoverageNode = $.zero.find(customize.children, { 'name': 'Embroidery Coverage' });
                        }
                        else {
                            this.quantityNode = null;
                            this.embroideryCoverageNode = null;
                        }

                        if (this.quantityNode != null && this.quantityNode.children != null) {
                            this.orderItem.quantity = this.quantityNode.children[0].name;
                        }
                        else {
                            this.orderItem.quantity = '';
                        }

                        this.specialOptionNode = $.zero.find(productItem.children, { 'name': 'Special Options' });

                        if (this.specialOptionNode !== null) {
                            this.backingNode = $.zero.find(this.specialOptionNode.children, { 'name': 'Backing' });
                            this.borderAndEdgeNode = $.zero.find(this.specialOptionNode.children, { 'name': 'Border & Edge' });
                        }

                        //todo:和初始化上传有冲突，无法直接使用之前的
                        this.$nextTick(function () {

                            form.val('quoteForm', {
                                "size": '3'
                            });

                            form.val('quoteForm', {
                                'embroideryCoverage': '75%'
                            });

                            form.render();
                        });
                    },
                    getName: function (item) {
                        return item.name + (item.title != null ? ' ' + item.title : '');
                    },
                    getSizeName: function (item) {
                        return item.name + (item.title != null ? ' inches ' + item.title + '' : ' inches');
                    }
                }
            });
        }
        //*************报价单结束***************//

        //头部表单弹窗
        $(".layui-colla-item").click(function () {
            $(this).addClass("sel").siblings().removeClass("sel");
        }) //pricing页面banner下方 手风琴添加选中效果


        //*************留言开始***************//
        var contactVue = new Vue({
            el: '#contactBox',
            data: {
                fileList: []
            }
        });

        //留言弹窗操作
        $(".chat").click(function () {
            //留言弹窗
            if ($(window).width() <= 768) {
                wiw = "3.8rem";
                wih = "4.7rem";
                po = "b";
            } else {
                wiw = "3.8rem";
                wih = "4.6rem";
                po = "rb";
            }
            var messageboxLayer = layer.open({
                title: false,
                skin: "mod_pop layerMsg",
                type: 1,
                offset: po,
                anim: 2,
                shade: 0,//不显示黑色遮罩
                isOutAnim: false,
                //scrollbar: false,
                area: [wiw, wih], //宽高
                content: $('footer .msg'),
                success: function (layero, index) {
                    $(".layerOnline").show();

                    //留言表单提交
                    form.on('submit(contactSubmit)', function (data) {
                        //---------文件合并--------
                        var fileList = [];
                        $("#contactUploadImgView input[name='uploadfile']").each(function (i) {
                            fileList.push($(this).val());
                        });
                        data.field.fileData = JSON.stringify(contactVue.fileList);

                        if (data.field.email === '') {
                            $.zero.showErrorMsg('Please Enter Your Email');
                            $("#contactBox input[name='email']").focus();
                            return;
                        }

                        var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                        if (!reg.test(data.field.email)) {
                            $.zero.showErrorMsg('Correct Mailbox Format');
                            $("#contactBox input[name='email']").focus();
                            return;
                        }
                        //-----------异步提交表单----------------
                        layer.load(2);
                        $.ajax({
                            type: "post",
                            url: "/api/addContact",
                            data: data.field,
                            success: function (msg) {
                                layer.closeAll('loading');
                                if (msg.success) {
                                    layer.close(messageboxLayer); //提交成功后关闭表单窗口 
                                    var successMsgLayer = layer.open({
                                        type: 1,
                                        skin: "mod_pop",
                                        title: false,
                                        closeBtn: 1,
                                        time: 10000,
                                        area: ['auto', 'auto'], //宽高
                                        shadeClose: true,
                                        content: "<div class='success_msg'><i class='iconfont'>&#xe663;</i><h5>Thank You!</h5><p class='desc'>We have received your submission. A representative will be in contact with you as soon as possible.</p></div>"
                                    });
                                }
                                else {
                                    $.zero.showValidationErrorMsg(msg);
                                }
                            },
                            error: function () {
                                layer.closeAll('loading');
                                $.zero.showErrorMsg('Sorry Server Lost');
                            }
                        });
                        //-----------异步提交表单----------------

                        return false;
                    }); //form

                },
                end: function (layero, index) {
                    $(".layerOnline").hide();
                }
            });
        });

        //留言图片上传
        var contactUploadFile = upload.render({
            elem: '#contactUploadFile', //绑定元素
            accept: 'file', //允许上传的文件类型
            //acceptMime: 'image/jpeg, image/jpg, image/png',//规定打开文件选择框时，筛选出的文件类型。
            multiple: false, //允许多文件上传
            exts: 'jpg|png|gif|bmp|jpeg|pdf|psd|tif|tiff|pic|pct|pga|eps|cdr|ai|hpgl|dxf|autocad',//允许上传的文件后缀
            //auto: false, //选完文件后不要自动上传
            //bindAction: '#xunjiaSubmit', //指定一个按钮触发上传
            url: '/api/upload', //上传接口
            number: 1,//设置同时可上传的文件数量
            size: 10000, //最大允许上传的文件大小
            progress: function (e, percent) {
                element.progress('progressBar', percent + '%');
            },
            choose: function (obj) {
                console.log('choose');
            },
            before: function (obj) {
                $('#contactUploadProgress').removeClass('hide');
            },
            done: function (res, index, upload) {
                if (res.success) {
                    contactVue.fileList.push(res.result);
                }
                else {
                    $.zero.showErrorMsg(res.error.message);
                }
                $('#contactUploadProgress').addClass('hide');
                element.progress('progressBar', '0%');
            },
            error: function () {
                $.zero.showErrorMsg(res.error.message);
                $('#contactUploadProgress').addClass('hide');
                element.progress('progressBar', '0%');
            }
        });
        //*************留言结束***************//

    }); //use layui初始化结束

    function isMobile() {
        var userAgentInfo = navigator.userAgent;

        var mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];

        var mobile_flag = false;

        //根据userAgent判断是否是手机
        for (var v = 0; v < mobileAgents.length; v++) {
            if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
                mobile_flag = true;
                break;
            }
        }

        var screen_width = window.screen.width;
        var screen_height = window.screen.height;

        //根据屏幕分辨率判断是否是手机
        if (screen_width < 500 && screen_height < 800) {
            mobile_flag = true;
        }

        return mobile_flag;
    }

}); //jquery

